<template>
  <div class="page-container">
    <div class="info-container_header">
      <svg class="icon" @click="handleCancel" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4136">
        <path
          d="M499.498667 225.834667a42.666667 42.666667 0 0 1 0 60.330666L316.330667 469.333333H810.666667a42.666667 42.666667 0 1 1 0 85.333334H316.330667l183.168 183.168a42.666667 42.666667 0 1 1-60.330667 60.330666l-256-256a42.666667 42.666667 0 0 1 0-60.330666l256-256a42.666667 42.666667 0 0 1 60.330667 0z"
          p-id="4137"
        />
      </svg>

      <div class="title">结算详情</div>
    </div>
    <div class="info-container" v-loading="loading">
      <div class="info-container_body">
        <el-collapse :model-value="['basic']" style="padding:10px">
          <el-collapse-item title="结算摘要" name="basic">
            <el-form ref="refFrom" label-position="top" class="padding">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="结算状态">
                    <dict-tag :options="dict.settle_status" :value="currentItem.status" />

                    <!-- {{$common.marchType(currentItem.status,dict.settle_status)}} -->
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="用户名称">
                    {{currentItem.vendorName}}
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="结算周期"> {{currentItem.timeFrom}}-{{currentItem.timeTo}} </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="结算方式">
                    <dict-tag :options="dict.esettle_type" :value="currentItem.settleType" />
                    <!-- {{$common.marchType(currentItem.settleType,dict.esettle_type)}} -->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="结算内容">
                    <dict-tag :options="dict.settle_contents" :value="currentItem.settleContents" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="收入合计(元)"> {{currentItem.totalRevenue/100.0}} </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="结算金额(元)">
                    {{currentItem.totalAmount/100.0}}
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="调平金额(元)">
                    {{currentItem.adjustAmount/100.0}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="结算时间"> {{currentItem.createTime}}-{{currentItem.finishTime}} </el-form-item>
                </el-col>
                <el-col :span="18">
                  <el-form-item label="累计结算额(元)">
                    {{currentItem.vendorPayedAmount/100.0}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-upload
                    class="upload-demo"
                    :action="uploadUrl"
                    :limit="1"
                    :data="uploadData"
                    :before-upload="beforeUpload1"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                  >
                    <el-button type="primary">上传凭证</el-button>
                    <!--  -->
                  </el-upload>
                  <el-upload
                    class="upload-demo"
                    :action="uploadUrl"
                    :limit="1"
                    :data="uploadData"
                    :before-upload="beforeUpload2"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                  >
                    <el-button type="primary">上传发票</el-button>
                    <!--  -->
                  </el-upload>
                  <el-button type="primary" @click="handleAdjust()">调平</el-button>
                  <el-button type="primary" @click="handleRedo()">重算</el-button>
                  <el-button type="danger" @click="handleUndo()">作废</el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-collapse-item>
          <el-collapse-item title="合同摘要" name="1">
            <ContractAbstract ref="contractAbstract" :info="currentItem.contract"></ContractAbstract>
          </el-collapse-item>
          <el-collapse-item title="结算栏" name="2">
            <List ref="adjust" :data="currentItem"></List>
            <!-- <Log ref="log" :data="currentItem"></Log> -->
          </el-collapse-item>
          <el-collapse-item title="调平栏" name="3">
            <Adjust ref="adjust" :data="currentItem"></Adjust>
            <!-- <Log ref="log" :data="currentItem"></Log> -->
          </el-collapse-item>
          <el-collapse-item title="附件栏" name="4">
            <el-form ref="refFrom" label-position="top" class="demo">
              <el-form-item label="转账凭证">
                <div class="fileInfo" v-for="(file,index) in currentItem.attachmentVos" :key="index">
                  <div v-if="file.type==1" @click="showFile(file.ossId)">
                    <img src="@/assets/images/light.svg" />
                    <div class="title">
                      <el-link type="danger">{{file.name}}</el-link>
                      <el-icon @click="removeFile(file.id)"><Delete /></el-icon>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="发票">
                <div class="fileInfo" v-for="(file,index) in currentItem.attachmentVos" :key="index">
                  <div v-if="file.type==2" @click="showFile(file.ossId)">
                    <img src="@/assets/images/light.svg" />
                    <div class="title">
                      <el-link type="danger">{{file.name}}</el-link>
                      <el-icon @click="removeFile(file.id)"><Delete /></el-icon>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <!-- <Log ref="log" :data="currentItem"></Log> -->
        </el-collapse>
      </div>
    </div>

    <el-drawer :title="dom.rightComponent.title" v-model="dom.rightComponent.show" direction="rtl" class="demo-drawer" :close-on-click-modal="false">
      <component
        ref="rightComponent"
        :is="dom.rightComponent.companentName"
        :data="currentItem"
        @hideRight="dom.rightComponent.show = false;init();"
      ></component>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import { defineAsyncComponent } from 'vue';
import { get, upload, delAttachment, redo, undo } from '@/api/operation/vendorSettlement/index';
import { useRouter } from 'vue-router';
import { globalHeaders } from '@/utils/request';
import { getVendor } from '@/api/vendor/index';
import { getContract } from '@/api/operation/contract/index';

export default {
  components: {
    List: defineAsyncComponent(() => import('./list.vue')),
    Adjust: defineAsyncComponent(() => import('./adjust.vue')),
    ContractAbstract: defineAsyncComponent(() => import('@/views/operation/contract/info/info-model.vue')),
    AdjustEdit: defineAsyncComponent(() => import('../adjust/edit.vue'))
  },

  mounted() {
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    this.proxy = proxy;
    this.dict = toRefs<any>(this.proxy?.useDict('esettle_type', 'settle_status', 'settle_contents'));

    const route = useRoute();
    this.currentItem.settlementId = route.query.id;

    this.init();
  },
  data() {
    return {
      loading: false,
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/biz-vendor/vendorSettlement/attachment/upload',
      headers: globalHeaders(),
      proxy: null,
      uploadData: {},
      currentItem: {},
      dict: {},
      dom: {
        proxy: null,
        rightComponent: {
          show: false,
          title: '',
          companentName: ''
        }
      }
    };
  },
  created() {},
  methods: {
    init() {
      let id = this.currentItem.settlementId;
      this.get(id);
    },

    get(id) {
      this.loading = true;
      // this.currentItem = {
      //   settlementId: '1779347872563597312',
      //   vendorId: '1774632645766758401',
      //   contractId: null,
      //   timeFrom: '2024-04-01 12:00:00',
      //   timeTo: '2024-04-14 12:00:00',
      //   bonusAmount: 0,
      //   motivationAmount: 0,
      //   electricityAmount: 0,
      //   adjustAmount: 0,
      //   totalAmount: 0,
      //   finishTime: null,
      //   withdrawTime: null,
      //   status: '2',
      //   attachmentVos: null
      // };

      get(id)
        .then((res) => {
          this.loading = false;

          let data = res.data;
          this.currentItem = data;

          this.$refs['adjust'].init(data);

          let contaracId = this.currentItem.contractId;
          if (contaracId) this.getContaracInfo(contaracId);

          let vendorId = this.currentItem.vendorId;
          if (vendorId) this.getVendor(vendorId);
        })
        .catch((e) => {
          this.loading = false;
        });
    },

    //合同详情
    getContaracInfo(id) {
      getContract(id)
        .then((res) => {
          this.loading = false;
          if (res.code == 200) {
            let contract = res.data;
            contract.validRange = contract.validFrom && contract.validTo ? [contract.validFrom, contract.validTo] : [];
            contract.attachments = (contract.attachments || []).map((it) => ({ ...it, url: it.ossId, ossId: it.id, fileName: it.name }));

            this.currentItem.contract = contract;
          } else {
          }
        })
        .catch((e) => {
          this.loading = false;
        });
    },

    /**
     * 获取酒店详情
     */
    getVendor(id) {
      getVendor(id)
        .then((res) => {
          this.loading = false;
          this.currentItem.vendorName = res.data.name;
        })
        .catch((e) => {
          this.loading = false;
        });
    },

    /**
     * 凭证上传前
     */
    beforeUpload1(uploadFile) {
      let id = this.currentItem.settlementId;
      this.uploadData = {
        name: uploadFile.name,
        type: 1,
        settlementId: id
      };
    },

    /**
     * 发票上传前
     */
    beforeUpload2(uploadFile) {
      let id = this.currentItem.settlementId;
      this.uploadData = {
        name: uploadFile.name,
        type: 2,
        settlementId: id
      };
    },

    /**
     * 上传成功
     */
    uploadSuccess(res) {
      // let id = this.currentItem.settlementId;

      // let data = {
      //   id: 0,
      //   settlementId: id,
      //   name: 0,
      //   ossId: 'http://deploy.cdlbyl.com/cps/files/2024/03/16/88a6f7d543574ae9b2b738860b934321.png',
      //   type: '1'
      // };
      // this.currentItem.attachmentVos.push(data);

      if (res.code == 200) {
        let data = res.data;
        this.currentItem.attachmentVos.push(data);
      } else {
        ElMessage.error(res.msg);
      }
    },

    /**
     * 上传失败
     */
    uploadError() {
      ElMessage.error('文件上传失败');
    },

    /**
     * 预览文件
     */

    showFile(ossid) {
      widow.open(ossid, '_blank');
    },

    /**
     * 移除文件
     */
    removeFile(id) {
      let attachmentVos = this.currentItem.attachmentVos;
      for (let i = 0; i < attachmentVos.length; i++) {
        if (attachmentVos[i].id == id) {
          attachmentVos.splice(i, 1);
          break;
        }
      }

      let ids = [id];
      delAttachment(ids)
        .then((res) => {
          if (res.code == 200) {
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    },

    /**
     * 匹配结果
     */
    marchType(value, types) {
      if (types == null) return '-';
      for (let i = 0; i < types.length; i++) {
        let type = types[i];
        if (type.value == value) return type.label;
      }
    },

    //返回
    handleCancel() {
      this.proxy?.$tab.closePage();
    },

    //调平
    handleAdjust() {
      this.dom.rightComponent.show = true;
      this.dom.rightComponent.title = '调平';
      this.dom.rightComponent.companentName = 'AdjustEdit';
    },

    //重算
    handleRedo() {
      this.loading = true;

      let row = this.currentItem;
      redo(row).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.init();
        } else {
          ElMessage.error(res.msg);
        }
      });
    },

    /**
     * 作废
     */
    handleUndo() {
      this.loading = true;

      let row = this.currentItem;
      undo(row).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.init();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.info-container_header {
  background: white;

  .icon {
    width: 30px;
    height: 30px;
    fill: blank;
  }
}

.upload-demo {
  float: left;
  margin-right: 10px;
}

.fileInfo {
  width: 80px;
  height: 100px;
  position: relative;
  float: left;
  margin: 5px;

  img {
    width: 80px;
    height: 80px;
    position: absolute;
    top: 0;
    left: 0;
  }

  .title {
    width: 100%;
    height: 20px;
    line-height: 20px;
    position: absolute;
    bottom: 0;
    left: 0;

    a {
    }

    i {
      color: red;
    }
  }
}
</style> 
